define(['jquery',"bbcare","dragula","bld/app/classify/programEdit.servers","bld/app/classify/programEdit.ui"],function($,$bb,$dragula,$servers,$ui){
    var programEdit = {};
    var obj = {},className = "programEditModal";
    var doctorName = JSON.parse($bb.getSessionStorage("account")).alias;
    var channelId = $bb.getChannelId();
 
    /**
     * 阶段下增加疗程回调函数
     */
    var ajaxAddStageCourse = function(data,stageId){
        obj.schemeVersion = data.data.schemeVersion;
        obj.status = "0";
        stageInit({"stageId":stageId});
    }

    /**
     * 我的疗程-拖拽插入疗程
     */
    var sortMyCourseList = function(courseId,courseVersion,courseName){
        var $domStage = $("#stageList .program.active");
        var seqNo = $("#myCourseList .course-list").length;
        var params = {
            "oprInfo":{
                "opCode": "2075",
                "opType": "3",
                "opNote": "【" + doctorName + "】医生给阶段【" + $domStage.html() + "】下增加疗程【" + courseName + "】",
                "channelType": "2",
                "channelId": channelId
            },
            "stageCourse":{
                "schemeId": obj.schemeId,
                "schemeVersion": obj.schemeVersion,
                "stageId": $domStage.attr('id'),
                "seqNo": seqNo,
                "courseVersion": courseVersion,
                "courseId": courseId
            }
        };
        // 阶段下增加疗程
        $servers.ajaxAddStageCourse(params,ajaxAddStageCourse,$domStage.attr('id'));
    };

    /**
     * 拖拽前函数
     */
    var drag = function(el){
        var index = $(el).children('.course-list-index').html();
        return index;
    };

    /**
     * 拖拽后处理时事件
     */
    var drop = function(el){
        if( $(el).parent().attr('id') == "myCourseList" ){
            if( $("#stageList").children("div.program").length == 0 ){
                $bb.toastShow('请先添加阶段');
                $(el).remove();
            }else{
                sortMyCourseList($(el).attr('id'),parseInt($(el).attr('data-version')),$(el).children('.course-list-course').html());
            };
        }
    };
    
    /**
     * 修改方案名称回调函数
     */
    var ajaxUpdateSchemeName = function(data,schemeName) {
        $bb.toastShow('修改方案名称成功');
        obj.schemeVersion = data.schemeVersion;
        obj.schemeName = schemeName;
    }

    /**
     * 修改方案名称事件
     */
    var onUpdateSchemeName = function() {
        var schemeName = $("#schemeName").val();
        var params = {
            "oprInfo":{
                "opCode": "2067",
                "opType": "3",
                "opNote": "【" + doctorName + "】医生修改方案【" + obj.schemeName + "】名称",
                "channelType": "2",
                "channelId": channelId
            },
            "schemeInfo":{
                "schemeName": schemeName,
                "classId": obj.classId,
                "diseaseId": obj.diseaseId,
                "libId": obj.libId,
                "id": obj.schemeId,
                "newVersion": obj.schemeVersion
            }
        };
        $servers.ajaxUpdateSchemeName(params,ajaxUpdateSchemeName,schemeName);
    }

    /**
     * 发布方案回调函数
     */
    var ajaxReleaseScheme = function(data) {
        $bb.toastShow('方案发布成功',1500);
        setTimeout(function() {
            $bb.openPage('bld_programList',{"id":obj.classId});
        }, 1500);
    }

    /**
     * 确认发布方案
     */
    var ajaxConfirmReleaseScheme = function(params){
        $servers.ajaxReleaseScheme(params,ajaxReleaseScheme);
    }

    /**
     * 发布方案
     */
    var releaseScheme = function() {
        var params = {
            "oprInfo":{
                "opCode": "2070",
                "opType": "3",
                "opNote": "【" + doctorName + "】医生发布方案【" + obj.schemeName + "】",
                "channelType": "2",
                "channelId": channelId
            },
            "schemeId":obj.schemeId,
            "schemeVersion":obj.schemeVersion,
        };
        $bb.toastConfirmShow(ajaxConfirmReleaseScheme,params,'确认将当前方案进行发布么？');
    }

    /**
     * 发布方案
     */
    var publishScheme = function(){
        $("#release").html('<button type="button" class="btn btn-warning" id="releaseBtn">发布方案</button>');
        // 发布方案
        $("#releaseBtn").unbind('click');
        $("#releaseBtn").click(releaseScheme);
    }

    /**
     * 增加阶段回调函数
     */
    var ajaxAddStage = function(data) {
        $('.' + className).modal('hide');
        $bb.toastShow('阶段添加成功');
        obj.schemeVersion = data.data.schemeVersion;
        obj.status = "0";
        stageInit({"stageId":data.data.stageId});
    }

    /**
     * 添加阶段事件
     */
    var addStage = function() {
        var stageName = $("#stageName").val();
        if( stageName == '' ) {
            $bb.toastShow('请填写阶段名称');
            return;
        }
        var seqNo = $('#stage .stage-null').length > 0 ? 1 : $('#stageList .program').length + 1;
        var params = {
            "oprInfo":{
                "opCode": "2071",
                "opType": "3",
                "opNote": "【" + doctorName + "】医生添加阶段【" + stageName + "】",
                "channelType": "2",
                "channelId": channelId
            },
            "stage":{
                "stageName": stageName,
                "schemeId": obj.schemeId,
                "schemeVersion": obj.schemeVersion,
                "seqNo": seqNo
            }
        };
        $servers.ajaxAddStage(params,ajaxAddStage);
    }
        
    /**
     * 添加阶段
     */
    var onAddStage = function() {
        $bb.modal({
            "className": className,
            "tit": "请输入阶段名称",
        }, function() {
            $ui.stageForm({
                "dom": $("." + className + " .modal-body"),
            });
            $("." + className).modal("show");
            $("#add").unbind('click');
            $("#add").click(addStage);
        });
    }

    /**
     * 修改阶段回调函数
     */
    var ajaxUpdateStageName = function(data,stageId) {
        $('.' + className).modal('hide');
        $bb.toastShow('阶段名称修改成功');
        obj.schemeVersion = data.schemeVersion;
        obj.status = "0";
        stageInit({"stageId":stageId});
    }

    /**
     * 修改阶段事件
     */
    var onUpdateStage = function() {
        var stageName = $("#stageName").val();
        if( stageName == '' ){
            $bb.toastShow('请填写阶段名称');
            return;
        }
        var $domStage = $("#stageList .program.active");
        var params = {
            "oprInfo":{
                "opCode": "2072",
                "opType": "3",
                "opNote": "【" + doctorName + "】医生修改阶段【" + $domStage.html() + "】",
                "channelType": "2",
                "channelId": channelId
            },
            "stage":{
                "id": $domStage.attr('id'),
                "stageName": stageName,
                "schemeId": obj.schemeId,
                "schemeVersion": obj.schemeVersion,
                "seqNo": parseInt( $domStage.attr('data-seqNo') )
            }
        };
        $servers.ajaxUpdateStageName(params,ajaxUpdateStageName,$domStage.attr('id'));
    }

    /**
     * 编辑阶段
     */
    var onModifyClick = function() {
        var stageName = $("#stageList .program.active").html();
        $bb.modal({
            "className": className,
            "tit": "请输入阶段名称",
        }, function() {
            $ui.stageForm({
                "dom": $("." + className + " .modal-body"),
                "stageName":stageName
            });
            $("." + className).modal("show");
            $("#modify").unbind('click');
            $("#modify").click(onUpdateStage);
        });
    }

    /**
     * 删除阶段回调函数
     */
    var ajaxDeleteStage = function(data) {
        $bb.toastShow('删除成功');
        obj.schemeVersion = data.schemeVersion;
        obj.status = "0";
        stageInit();
    }

    /**
     * 确认删除阶段
     */
    var confirmDeleteStage = function(params) {
        $servers.ajaxDeleteStage(params,ajaxDeleteStage);
    }

    /**
     * 删除阶段
     */
    var onDelClick = function() {
        var $domStage = $("#stageList .program.active");
        var params = {
            "oprInfo":{
                "opCode": "2073",
                "opType": "3",
                "opNote": "【" + doctorName + "】医生删除阶段【" + $domStage.html() + "】",
                "channelType": "2",
                "channelId": channelId
            },
            "stage":{
                "schemeId": obj.schemeId,
                "schemeVersion": obj.schemeVersion,
                "seqNo": parseInt( $domStage.attr('data-seqNo') ),
                "id": $domStage.attr('id')
            }
        };
        $bb.toastConfirmShow(confirmDeleteStage,params,"是否确认删除" + $domStage.html());
    }

    /**
     * 移动阶段回调函数
     */
    var ajaxMoveStage = function(data,stageId){
        $bb.toastShow('阶段移动成功');
        obj.schemeVersion = data.schemeVersion;
        obj.status = "0";
        stageInit({"stageId":stageId});
    }

    /**
     * 移动阶段
     */
    var onMoveStage = function() {
        var moveDirection = $(this).data("moveDirection");
        var $stageDom = $("#stageList .program.active");
        if( moveDirection == "up" ){
            var str = "前移";
            if( !$stageDom.prevAll().length ){
                $bb.toastShow('已经在最前面啦');
                return;
            }
        }else if( moveDirection == "down" ){
            var str = "后移";
            if( !$stageDom.nextAll().length ){
                $bb.toastShow('已经在最后面啦');
                return;
            }
        }
        var stageId = $stageDom.attr('id');
        var params = {
            "oprInfo":{
                "opCode": "2074",
                "opType": "3",
                "opNote": "【" + doctorName + "】"+ str +"阶段【" + $stageDom.html() + "】",
                "channelType": "2",
                "channelId": channelId
            },
            "stage":{
                "schemeId": obj.schemeId,
                "schemeVersion": obj.schemeVersion,
                "id": stageId,
                "seqNo": parseInt($stageDom.attr('data-seqNo')),
                "moveDirection": moveDirection,
            }
        };
        $servers.ajaxMoveStage(params,ajaxMoveStage,stageId);
    }

    /**
     * 删除疗程回调函数
     */
    var ajaxDeleteCourse = function(data,stageId){
        $bb.toastShow('删除成功');
        obj.schemeVersion = data.schemeVersion;
        obj.status = "0";
        stageInit({"stageId":stageId});
    }

    /**
     * 确认删除疗程
     */
    var confirmDeleteCourse = function(params){
        $servers.ajaxDeleteCourse(params,ajaxDeleteCourse);
    }

    /**
     * 删除疗程事件
     */
    var onDeleteCourse = function() {
        var $stageDom = $("#stageList .program.active");
        var $courseDom = $(this).parents(".course-list");
        var courseName = $courseDom.children('.course-list-course').html();
        var params = {
            "oprInfo":{
                "opCode": "2076",
                "opType": "3",
                "opNote": "【" + doctorName + "】医生删除疗程【" + courseName + "】",
                "channelType": "2",
                "channelId": channelId
            },
            "stageCourse":{
                "schemeId": obj.schemeId,
                "schemeVersion": obj.schemeVersion,
                "stageId": $stageDom.attr('id'),
                "seqNo": parseInt($courseDom.attr('data-seqNo')),
                "id": $courseDom.attr('id'),
            },
        };
        $bb.toastConfirmShow(confirmDeleteCourse,params,"确认是否删除？")
    }

    /**
     * 移动疗程回调函数
     */
    var ajaxMoveCourse = function(data,stageId) {
        $bb.toastShow('设置成功');
        obj.schemeVersion = data.schemeVersion;
        obj.status = "0";
        stageInit({"stageId":stageId});
    }

    /**
     * 上下移动阶段中的疗程
     */
    var onMoveCourse = function(){
        var moveDirection = $(this).data("moveDirection");
        var $courseDom = $(this).parents(".course-list");
        if( moveDirection == "up" ){
            if( !$courseDom.prevAll().length ){
                $bb.toastShow('已经在最前面啦');
                return;
            }
        }else if( moveDirection == "down" ){
            if( !$courseDom.nextAll().length ){
                $bb.toastShow('已经在最后面啦');
                return;
            }
        }
        var courseName = $courseDom.children('.course-list-course').html();
        var stageId = $("#stageList .program.active").attr('id');
        var params = {
            "oprInfo":{
                "opCode": "2077",
                "opType": "3",
                "opNote": "【" + doctorName + "】医生下移疗程【" + courseName + "】",
                "channelType": "2",
                "channelId": channelId
            },
            "stageCourse":{
                "schemeId": obj.schemeId,
                "schemeVersion": obj.schemeVersion,
                "stageId": stageId,
                "seqNo": parseInt( $courseDom.attr('data-seqNo') ),
                "id": $courseDom.attr('id'),
                "moveDirection": moveDirection,
            }
        };
        $servers.ajaxMoveCourse(params,ajaxMoveCourse,stageId);
    }

    /**
     * 选择阶段
     */
    var stageListClick = function() {
        $(this).addClass('active').siblings().removeClass('active');
        var data = $(this).data('data');
        var index = $(this).index();
        $ui.stageCourse({
            "id": "myCourseList",
            "list": data.schemePO.stageInfoPOs[index].stageCourseInfoPOs
        });
        // 上移疗程
        $(".course-list-upBtn").unbind('click');
        $(".course-list-upBtn").data("moveDirection","up");
        $(".course-list-upBtn").click(onMoveCourse);
        // 下移疗程
        $(".course-list-downBtn").unbind('click');
        $(".course-list-downBtn").data("moveDirection","down");
        $(".course-list-downBtn").click(onMoveCourse);
        // 删除疗程
        $(".course-list-delBtn").unbind('click');
        $(".course-list-delBtn").click(onDeleteCourse);
    }

    /**
     * 查询方案详情成功后的回调函数
     */
    var ajaxQueryScheme = function(data,arg){
        $ui.stage({
            "id": "stage",
            "list": data.schemePO.stageInfoPOs
        });
        // 添加阶段
        $("#addStage").unbind('click');
        $("#addStage").click(onAddStage);
        // 存在阶段的情况下
        if( data.schemePO.stageInfoPOs && data.schemePO.stageInfoPOs.length > 0 ){
            $("#stageList div").unbind('click');
            $("#stageList div").data('data',data);
            $("#stageList div").click(stageListClick);
            // 选中某个阶段
            var index = arg && arg.stageId ? $servers.getIndexByStageId(data.schemePO.stageInfoPOs,arg.stageId) : 0;
            $("#stageList div").eq(index).click();
            // 前移
            $("#upStage").unbind('click');
            $("#upStage").data("moveDirection","up");
            $("#upStage").click(onMoveStage);
            // 后移
            $("#downStage").unbind('click');
            $("#downStage").data("moveDirection","down");
            $("#downStage").click(onMoveStage);
            // 编辑
            $("#modifyStage").unbind('click');
            $("#modifyStage").click(onModifyClick);
            // 删除
            $("#delStage").unbind('click');
            $("#delStage").click(onDelClick);
        }
    }

    /**
     * 跳转到疗程编辑页面
     */
    var onGoCourseEdit = function() {
		var $stageDom = $("#stageList .program.active");
        var $courseDom = $(this).parents(".course-list");
        var index = $(this).parents(".course-list").index();
        var courses = $(this).data("courses");

        var obj = $bb.getPageParams();
        var params = {
            "courseName":courses[index].course_name,
            "id":courses[index].id,
            "courseVersion":courses[index].course_version,
            "status":courses[index].status,
            "source":{
                "name":"bld_programEdit",
                "params":obj
            }
        };
        $bb.openPage('bld_courseEdit', params);
    }

    /**
     * 查询疗程回调函数
     */
    var ajaxQueryAllCourse = function(data){
        $ui.queryAllCourse({
            "id": "courseStore",
            "list": data.rows
        })
        $(".course-list-editBtn").unbind('click');
        $(".course-list-editBtn").data("courses",data.rows);
        $(".course-list-editBtn").click(onGoCourseEdit);
    }

    /**
     * 切换方案下的疗程
     */
    var onChangeCourse = function(){
        var classId = $("#classify").val();
        var params = {
            "queryCriteria":{
                "schemeId": classId,
                "status":"1" // 已发布
            }
        };
        $servers.ajaxQueryAllCourse(params,ajaxQueryAllCourse);
    }

    /**
     * 获取所有方案分类回调函数
     */
    var ajaxQueryAllSchemeClass = function(data){
        $ui.schemeClassAll({
            "id": "classify",
            "list": data.schemeClassInfos
        });
        $('#classify').unbind("change");
        $('#classify').bind("change",onChangeCourse);
        $('#classify').eq(0).change();
    }

    /**
     * 添加疗程回调函数
     */
    var ajaxAddCourse = function(data,schemeClassId){
        $('.' + className).modal('hide');
        $("#classify").val(schemeClassId);
        $("#classify").trigger("change");
    }

    /**
     * 查询疗程库分类
     */
    var ajaxCourseClassCallBack = function(data){
        if( data.rows.length > 0 ){
            var courseName = $("#tpl_courseName").val();
            if( courseName == "" ){
                $bb.toastShow("请输入疗程名称！"); 
            }else{                
                var scheme_id = $("#tpl_classId").val();
                var courseIntro = $("#tpl_courseIntro").val();
                var courseType = $("#tpl_courseType").val();
                var groupValue = $("#tpl_group").val();
                var doctorName = JSON.parse($bb.getSessionStorage("account")).alias;
                var channelId = $bb.getChannelId();
                var params = {
                    "oprInfo":{
                        "opCode": "2050",
                        "opType": "3",
                        "opNote": "【" + doctorName + "】医生添加疗程【" + courseName + "】",
                        "channelType": "2",
                        "channelId": channelId
                    },
                    "course":{
                        "courseName": courseName,
                        "classId": data.rows[0].id,
                        "courseIntro": courseIntro,
                        "scheme_id": scheme_id
                    },
                    "courseVersion":{
                        "courseType": courseType,
                        "groupType": "0",
                        "groupValue": groupValue
                    }
                };
                $servers.ajaxAddCourse(params,ajaxAddCourse,scheme_id);
            }
        }else{
            $bb.toastShow("该系统下没有配置疗程分类，请配置！");
        }
    }

    /**
     * 添加疗程
     */
    var addCourse = function() {
        $servers.ajaxCourseClass(ajaxCourseClassCallBack);
    }

    /**
     * 模态框方案分类回调函数
     */
    var ajaxAllScheme = function(data) {
        $bb.modal({
            "className": className,
            "tit": "添加疗程",
        }, function() {
            $ui.addCourse({
                "dom": $("." + className + " .modal-body"),
                "schemeClass":data.schemeClassInfos
            });
            $("." + className).modal("show");
            $("#add").unbind("click");
            $("#add").bind("click", addCourse);
        });
    }

    /**
     * 添加疗程事件
     */
    var onAddCourse = function(){
        $servers.ajaxQueryAllSchemeClass(ajaxAllScheme);
    }

    /**
     * 阶段初始化
     */
    var stageInit = function(arg){
        if( obj.status == "0" ) publishScheme();
        // 查询方案详情
        var params = {
            "schemeId":obj.schemeId,
            "schemeVersion":obj.schemeVersion,
        };
        $servers.ajaxQueryScheme(params,ajaxQueryScheme,arg);
    }

    programEdit.init = function() {
        obj = $bb.getPageParams();
        // 方案名称
        $("#schemeName").val(obj.schemeName);
        stageInit();
        // 修改方案名称
        $("#save").unbind("click");
        $("#save").click(onUpdateSchemeName);
        // 跳转到方案分类
        $("#classifyHref").unbind("click");
        $("#classifyHref").click(function() {
            $bb.openPage("bld_classifyList");
        });
        // 跳转到方案库
        $("#programHref").unbind("click");
        $("#programHref").click(function() {
            $bb.openPage("bld_programList",{"id":obj.classId});
        });
        // 请求所有方案分类
        $servers.ajaxQueryAllSchemeClass(ajaxQueryAllSchemeClass);
        // 拖拽
        $dragula([myCourseList,courseStore],{copy:true}).on('drag',function(el){
            drag(el);
        }).on('drop',function(el){
            drop(el);
        });
        // 添加疗程
        /*$("#addCourse").unbind("click");
        $("#addCourse").click(onAddCourse);*/
    }

    return programEdit;
});